//
//  KCommandManage.m
//  Keping
//
//  Created by 柯平 on 2017/6/18.
//  Copyright © 2017年 柯平. All rights reserved.
//

#import "KCommandManage.h"

@implementation KCommandManage

+(instancetype)sharedInstance
{
    static dispatch_once_t onceToken;
    static KCommandManage* _instance;
    dispatch_once(&onceToken, ^{
        _instance = [[self alloc] init];
    });
    return _instance;
}

-(instancetype)init
{
    self = [super init];
    if (self) {
        self.commandQueue = [NSMutableArray array];
    }
    return self;
}

+(void)executeCommand:(id<Command>)cmd observer:(id<CommandDelegate>)observer
{
    if (cmd && ![self isExecutingCommand:[cmd class]]) {
        [[KCommandManage sharedInstance] executeCommand:cmd observer:observer];
    }
}

-(void)executeCommand:(id<Command>)cmd observer:(id<CommandDelegate>)observer
{
    [self.commandQueue addObject:cmd];
    cmd.delegate = observer;
    [cmd execute];
}

+(void)executeCommand:(id<Command>)cmd completeBlock:(CommandCallBackBlock)completeBlock
{
    if (cmd && ![self isExecutingCommand:[cmd class]]) {
        [[KCommandManage sharedInstance] executeCommand:cmd completeBlock:completeBlock];
    }
}

-(void)executeCommand:(id<Command>)cmd completeBlock:(CommandCallBackBlock)completeBlock
{
    [self.commandQueue addObject:cmd];
    cmd.callbackBlock = completeBlock;
    [cmd execute];
}

+(void)cancelCommand:(id<Command>)cmd
{
    if (cmd) {
        [cmd cancel];
        [[KCommandManage sharedInstance].commandQueue removeObject:cmd];;
    }
}

+(void)cancelCommandByClass:(Class)cls
{
    NSArray* tempArr = [NSArray arrayWithArray:[KCommandManage sharedInstance].commandQueue];
    for (id<Command>cmd in tempArr) {
        if ([cmd isKindOfClass:cls]) {
            [cmd cancel];
            [[KCommandManage sharedInstance].commandQueue removeObject:cmd];
        }
    }
}

+(void)cancelCommandByObserver:(id)observer
{
    if (!observer) {
        return;
    }
    
    NSArray* tempArr = [NSArray arrayWithArray:[KCommandManage sharedInstance].commandQueue];
    for (id<Command> cmd in tempArr) {
        if (cmd.delegate == observer) {
            [cmd cancel];
            [[KCommandManage sharedInstance].commandQueue removeObject:cmd];
        }
    }
}

+(id)isExecutingCommand:(Class)cls
{
    NSArray* tempArr = [NSArray arrayWithArray:[KCommandManage sharedInstance].commandQueue];
    for (id cmd in tempArr) {
        if ([cmd isKindOfClass:cls]) {
            return cmd;
        }
    }
    return nil;
}

@end
